package com.onegroup.service.impl;

import com.onegroup.common.enums.ResponseStatusEnum;
import com.onegroup.common.exception.MyCustomException;
import com.onegroup.mapper.ApplicationMapper;
import com.onegroup.mapper.MenuMapper;
import com.onegroup.pojo.Application;
import com.onegroup.pojo.dto.ApplicationDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author: 曾雪斌
 * @Description:
 * @History:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名获取数据库中的系统用户
        Application application = applicationMapper.selectUserByUsername(username);
        if (Objects.isNull(application)) {
            throw new MyCustomException(ResponseStatusEnum.USER_ERROR);
        }

        // 返回权限标识
        List<String> perms = menuMapper.selectPermsByUserId(application.getAppId());

        // 返回UserDetails
        return new ApplicationDto(application, perms);
    }
}
